<script setup lang="ts">
import { selectModule } from '@/api/develop'
import { reactive, onMounted, onBeforeMount } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStore } from '@/store/modules/locale'
const emit = defineEmits(['nodeClick'])
const { t } = useI18n()
const localeStore = useLocaleStore()

const state = reactive({
  modules: [{}],
  curIds: '',
  title: t('common.modules'),
  treeProps: {
    children: 'children',
    label: 'moduleName'
  }
})

onBeforeMount(() => {
  const curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.treeProps.label = 'enName'
  } else if (curLang == 'zh_HK') {
    state.treeProps.label = 'hkName'
  }
})

onMounted(async () => {
  const moduleList = await selectModule()
  state.modules = []
  //取一级模块
  for (const module of moduleList) {
    const row = module as any
    if (row.level == 1) {
      state.modules.push(row)
      //递归处理子节点
      convertData(row, moduleList)
    }
  }
})

/**
 * @description  递归处理子节点
 * @param parent 父节点
 */
const convertData = (parent: any, data: []) => {
  for (const rowAny of data) {
    const row = rowAny as any
    if (row.parentId == parent.moduleId) {
      if (!parent.children) {
        parent.children = []
      }
      parent.children.push(row)
      //递归处理子节点
      convertData(row, data)
    }
  }
}
//树节点单击事件
const handleNodeClick = (data) => {
  state.curIds = ''
  getModuleIds(data)
  emit('nodeClick', state.curIds)
}

//取当前节点及其所有子节点ID
const getModuleIds = (node) => {
  if (state.curIds.length == 0) {
    state.curIds = node.moduleId
  } else {
    state.curIds += ',' + node.moduleId
  }
  if (!node.children) {
    return
  }
  for (const child of node.children) {
    getModuleIds(child)
  }
}
</script>
<template>
  <div class="treeDiv">
    <div class="treeTitle">{{ state.title }}</div>
    <el-tree
      :data="state.modules"
      :props="state.treeProps"
      @node-click="handleNodeClick"
      class="treeObject"
    />
  </div>
</template>

<style scoped>
.treeTitle {
  text-align: center;
  letter-spacing: 2px;
  line-height: 25px;
  font-size: 14px;
  background-color: #eee;
  color: #666;
}
.treeDiv {
  min-height: 300px;
  margin-top: 8px;
  /*height: calc(100vh - 156px);*/
  height: calc(100% - 10px);
  width: 100%;
  border: 1px solid #ddd;
  background-color: white;
}
.treeObject {
  width: 100%;
}
:deep(.el-tree-node__label) {
  font-size: 13px;
}
</style>
